package com.edu.tool.util;

import org.springframework.util.StringUtils;

public class KeyGenerator {
    static String incrId(String Id){
        int  size = Id.length();
        char id[] = Id.toCharArray();

        StringBuilder IdSb = new StringBuilder();

        int  j;
        int delimPos = 0;
        char digit,tempDigit;

        boolean bCarry     = true,
                bSeenDelim = true;

        if(StringUtils.isEmpty(Id)){
            return "0";
        }

        for( j = size -1; bCarry && j>=0; j-- ) {
            digit = id[j];
            if (digit == '-') {
                if (bSeenDelim) {
                     throw new RuntimeException("invalid row format");
                } else {
                    delimPos = j;
                    bSeenDelim = true;
                }
            }

            if (bSeenDelim)
            {
                continue;
            }

            if (digit < '9' && digit >= '0')
            {
                digit++;
                bCarry = false;
            }
            else if (digit == '9')
            {
                digit = 'A';
                bCarry = false;
            }
            else if (digit < 'Z' && digit >= 'A')
            {
                digit++;
                bCarry = false;
            }
            else if (digit == 'Z')
            {
                digit = '0';
                bCarry = true;
            }
            else
            {
                //error
            }
            id[j] = digit;
        }

        if (bCarry)
        {
            if (bSeenDelim)
            {
                // If this is a row id (ie prefix "-" suffix),
                // id = prefix + "1" + modified suffix

                digit = id[delimPos + 1];

                id[delimPos + 1 ] = '1';

                for (j = delimPos + 2; j < size ; j++)
                {
                    tempDigit = id[j];

                    id[j] = digit;

                    digit = tempDigit;
                }



                IdSb.append(id);
                IdSb.append(digit);

                return IdSb.toString();
            }
            else
            {


                IdSb.append("1");
                IdSb.append(id);

                return IdSb.toString();
            }
        }
        else
        {
            IdSb.append(id);

            return IdSb.toString();
        }

    }
}
